import type { BasicUserInfo, Recordable } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { ElNotification } from 'element-plus';
import { defineStore } from 'pinia';

import { getUserInfoApi, logoutApi, tokenApi } from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 调用验证码组件
   * @param success 成功回调
   */
  const createCaptcha = (success: (res?: any, c?: any, tac?: any) => void) => {
    const captchaConfig = {
      // 请求验证码接口 type支持 SLIDER、ROTATE、WORD_IMAGE_CLICK、CONCAT 等验证码类型
      requestCaptchaDataUrl: `${
        import.meta.env.VITE_GLOB_API_URL
      }/auth/captcha/generate?type=ROTATE`,
      // 验证验证码接口
      validCaptchaUrl: `${import.meta.env.VITE_GLOB_API_URL}/auth/captcha/check`,
      // 绑定的div
      bindEl: '#captcha-div',
      // 验证成功回调函数
      validSuccess: (res?: any, c?: any, tac?: any) => {
        success(res, c, tac);
      },
    };

    (window as any)
      .initTAC('/static/tac', captchaConfig, { logoUrl: null })
      .then((tac?: any) => {
        tac.init();
      });
  };

  /**
   * 密码登录
   * @param params
   * @param onSuccess
   */
  function loginByPassword(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    createCaptcha((res, _c, tac) => {
      tac.destroyWindow(); // 销毁验证码
      params.captchaId = res.data;
      authLogin('password', params, onSuccess);
    });
  }

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    grantType: string,
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    const userInfo: BasicUserInfo | null = null;
    try {
      loginLoading.value = true;
      const loginResult = await tokenApi(grantType, params);

      // 如果成功获取到 accessToken
      if (loginResult) {
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(loginResult?.access_token);
        accessStore.setRefreshToken(loginResult?.refresh_token);

        // 获取用户信息并存储到 accessStore 中
        const userInfo = await fetchUserInfo();

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(userInfo?.authorities ?? []);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(DEFAULT_HOME_PATH);
        }

        if (userInfo?.username) {
          ElNotification({
            message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.username}`,
            title: $t('authentication.loginSuccess'),
            type: 'success',
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  /**
   * 注销登录
   */
  async function logout() {
    try {
      await logoutApi();
    } finally {
      redirect2LoginPage(false);
    }
  }

  /**
   * 跳转登录页
   */
  async function redirect2LoginPage(redirect: boolean = true) {
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: BasicUserInfo | null = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    loginByPassword,
    fetchUserInfo,
    loginLoading,
    redirect2LoginPage,
    logout,
  };
});
